/**
 * 
 */
package cc.rico.tutorial.topic;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import cc.rico.tutorial.RabbitMQConnectionUtil;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

import lombok.extern.slf4j.Slf4j;

/**
 * @author rico
 *
 */
@Slf4j
public class ReceiveTopicLogs implements Runnable {
	private static final String EXCHANGE_NAME = "topicLogs";
	private static final String EXCHANGE_TYPE= "topic";
	
	private String routingKey;
	private Connection conn;

	public ReceiveTopicLogs(String routingKey, Connection conn) throws IOException, TimeoutException {
		this.routingKey = routingKey;
		this.conn = conn;
	}

	@Override
	public void run() {
		try {
			Channel channel = conn.createChannel();
			channel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE);
			
			String queueName = channel.queueDeclare().getQueue();
			channel.queueBind(queueName, EXCHANGE_NAME, routingKey);
			System.out.println(" [" + queueName + "-" + routingKey + "] Waiting for messages. To exit press CTRL+C");

			Consumer consumer = new DefaultConsumer(channel) {
				@Override
				public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
					String message = new String(body, "UTF-8");
					System.out.println(" [" + queueName + "-" + routingKey + "] Received '" + message + "'");
				}
			};
			channel.basicConsume(queueName, true, consumer);

			Thread.sleep(1000 * 10);
			RabbitMQConnectionUtil.close(channel);

		} catch (IOException | TimeoutException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param args
	 * @throws TimeoutException
	 * @throws IOException
	 * @throws InterruptedException
	 */
	public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
		Connection conn = RabbitMQConnectionUtil.getConnection();
		// * (star) can substitute for exactly one word.
		// # (hash) can substitute for zero or more words.
		new Thread(new ReceiveTopicLogs("#.log", conn)).start();
		new Thread(new ReceiveTopicLogs("console.#", conn)).start();
	}
}
